#include <stdio.h>
#include <string.h>
#include <sqlite3.h>
#include "../include/user.h"
#include "../include/database.h"

/* 将回调函数移到文件作用域 */

/* 用于 user_exists 的回调 */
static int exists_callback(void *data,int argc,char **argv, char**colName){
    int *exists = (int *)data;
    *exists = 1;
    return 0;
}

/* 用于 validate_user 的回调 */
static int valid_callback(void *data, int argc,char **argv,char **colName){

    int *valid = (int *)data;
    *valid = 1;
    return 0;
}

int add_user(const char *username, const char *password) {
    char sql[256];
    snprintf(sql, sizeof(sql), "INSERT INTO users (username, password) VALUES ('%s', '%s');", 
             username, password);
    return execute_sql(sql, NULL, NULL) == SQLITE_OK;
}

int user_exists(const char *username) {
    char sql[256];
    snprintf(sql, sizeof(sql), "SELECT 1 FROM users WHERE username = '%s';", username);
    
    int exists = 0;
    execute_sql(sql, exists_callback, &exists);
    return exists;
}

int validate_user(const char *username, const char *password) {
    char sql[256];
    snprintf(sql, sizeof(sql), "SELECT 1 FROM users WHERE username = '%s' AND password = '%s';", 
             username, password);
    
    int valid = 0;
    execute_sql(sql, valid_callback, &valid);
    return valid;
}

int is_admin(const char *username, const char *password) {
    return strcmp(username, ADMIN_USERNAME) == 0 && 
           strcmp(password, ADMIN_PASSWORD) == 0;
}